/*
 * parserpackage.c
 *
 *  Created on: 2013-5-13
 *      Author: xkaying
 */

#include "parserpackage.h"
#include "lexer.h"
#include "parser.h"
#include "../typedef/token.h"
#include "../typedef/package.h"

#include "parser.h"

Package *ParserPackage(Lexer *lexer,ProjectParser *parser)
{
	int state;
	state = 0;
	ptoken = LexerGetToken(lexer);
	Package *package;
	package=0;
	while (ptoken) {
		switch (state)
		{
			case 0: {
				switch (ptoken->type)
				{
					case TokenType_Comment: {
						ptoken = LexerGetToken(lexer);
						continue;
					}
					case TokenKey_PACKAGE: {
						state = 1;
						ptoken = LexerGetToken(lexer);
						continue;
					}
					default: {
						printf("文件必须先定义包.\n");
						return 0;
					}
				}
				printf("parser package状态机错误.状态%d.\n", state);
				return 0;
			}
			case 1: {
				//包名字
				switch (ptoken->type)
				{
					case TokenType_Variable: {
						state = 10;
						package = PackageInit(ptoken->name);
						//生成该包
						ptoken = LexerGetToken(lexer);
						continue;
					}
					default: {
						printf("包命名格式错误.\n");
						return 0;
					}
				}
				printf("parser package状态机错误.状态%d.\n", state);
				return 0;
			}
			case 10: {
				switch (ptoken->type)
				{
					case TokenType_Get: {
						state = 11;
						//生成该包
						ptoken = LexerGetToken(lexer);
						continue;
					}
						//表示包定义结束,进入包内容开始
					case TokenType_BlockStart:
					case TokenType_Comment: {
						return package;
					}
					case TokenType_End: {
						state = 0;
						package=0;
						printf("第%d行 警告:无效的包定义.\n", ptoken->line);
						ptoken = LexerGetToken(lexer);
						continue;
					}
					default: {
						printf("包命名格式错误.\n");
						return 0;
					}
				}
				printf("parser pacakge状态机错误.状态%d.\n", state);
				return 0;
			}
			case 11: {
				switch (ptoken->type)
				{
					case TokenType_Variable: {
						state = 10;
						//生成该包
						package = PackageAppend(package, ptoken->name);
						ptoken = LexerGetToken(lexer);
						continue;
					}
					default: {
						printf("包命名格式错误.\n");
						return 0;
					}
				}
				printf("parser状态机错误.状态%d.\n", state);
				return 0;
			}
			case 12: {
				switch (ptoken->type)
				{
					case TokenType_End: {
						state = 0;
						//释放已经生成的包
						package=0;
						printf("第%d行 警告:无效的包定义.\n", ptoken->line);
						ptoken = LexerGetToken(lexer);
						continue;
					}
					case TokenType_BlockStart:
					case TokenType_Comment: {
						return package;
					}
					default: {
						printf("包命名结束后,需要在{}中描述包内容.\n");
						return 0;
					}
				}
				printf("parser package状态机错误.状态%d.\n", state);
				return 0;
			}
			default:{
				printf("parser package状态机错误.状态:default.\n");
			}
		}
	}
	if(!package){
		//表示是一个完整的包定义.
		printf("不完整的包定义.\n");
	}
	return package;
}
